package com.example.excel;

import com.example.excel.pojo.BaseExcel;
import com.example.excel.resolve.ExcelResolveEachListener;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;

import java.io.*;
import java.util.Iterator;

public class ExcelRead {

    public static <T> BaseExcel<T> read(String originPath, ExcelResolveEachListener<T> resolveListener) {
        File file = new File(originPath);
        if (!file.isFile() || !file.exists()) {
            return null;
        }
        try {
            InputStream in = new FileInputStream(file);
            BaseExcel<T> data = readExcel(in, resolveListener);
            data.setFilePath(originPath);
            return data;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static <T> BaseExcel<T> readExcel(InputStream in, ExcelResolveEachListener<T> resolveListener) {
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(in);
            int sheetsNumber = workbook.getNumberOfSheets();
            for (int n = 0; n < sheetsNumber; n++) {
                Sheet sheet = workbook.getSheetAt(n);
                if (sheet == null || !resolveListener.resolveSheet(n, sheet)) {
                    continue;
                }
                Row row ; Cell cell;
                int startRow = sheet.getFirstRowNum();
                int endRow = sheet.getPhysicalNumberOfRows();
                for (int i = startRow; i <= endRow; i++) {
                    row = sheet.getRow(i);
                    if (row == null || !resolveListener.resolveRow(i, row)) continue;
                    Iterator<Cell> it = row.cellIterator();
                    while (it.hasNext()){
                        cell = it.next();
                        if(cell==null) continue;
                        resolveListener.resolve(n, i, cell.getColumnIndex(), cell);
                    }
                }
            }
        } catch (IOException | InvalidFormatException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(workbook);
            IOUtils.closeQuietly(in);
        }
        return resolveListener.getResult();
    }

}